﻿using CWD.BLL;
using CWD.DAL.DBUtility;
using CWD.EF;
using CWD.RPT;
using CWD.XSD;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Windows.Forms;
using ZXing;
using ZXing.Common;

namespace CWD
{
    public partial class frmMain : Form
    {
        int Id;
        public frmMain()
        {
            InitializeComponent();
        }

        private void tsbNewsheet_Click(object sender, EventArgs e)
        {
            string msg = "";
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "d:\\";
            openFileDialog1.Filter = "excel 表格 (*.xlsx)|*.xlsx|excel 表格 (*.xls)|*.xls|All files(*.*)|*>**";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    DataTable dt =CWD.Common.Common.ReadExcel(openFileDialog1.FileName);
                    PoMaterialBLL pmBll = new PoMaterialBLL();
                    PoMateriallistBLL pmsBll = new PoMateriallistBLL();
                    C_PoMaterial pm=InputPacket();
                    string ArrMsg = "";
                    List<C_PoMaterialList> lstPms = InputPacketList(dt,out msg,out ArrMsg);
                    if (msg != "")
                    {
                        MessageBox.Show(msg, "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    if (ArrMsg != "")
                    {
                        if(MessageBox.Show(ArrMsg+",您确定要继续吗？", "数据检查", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)!=DialogResult.Yes)
                            return;
                    }
                    bool bExist = false;
                    int continuecount = 0;
                    for (int i = 0; i < lstPms.Count; i++)
                    {
                        int podid = (int)lstPms[i].PoDid;
                        decimal qty = (decimal)lstPms[i].Qty;
                        var count = pmsBll.GetQuery().Where(p => p.PoDid == podid && p.Qty == qty).Count();
                        if (count > 0)
                        {
                            bExist = true;
                            continuecount++;
                            if (continuecount >= 3)
                            {
                                MessageBox.Show("当前单据已经导入，请检查！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                        else {
                            bExist = false;
                            continuecount = 0;
                        }
                        if (i > 10)
                            break;
                    }
                    using (TransactionScope acope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 10, 0)))
                    {
                        try
                        {
                            pmBll.Add(pm);
                            for (int i = 0; i < lstPms.Count; i++)
                            {
                                lstPms[i].Id = pm.Id;
                                pmsBll.Add(lstPms[i]);
                            }
                            acope.Complete();
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                            return;
                        }
                        finally
                        {
                            acope.Dispose();
                        }
                    }                    
                    ShowPackets(pm.Id);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("打开文件出错：" + ex.Message);
                }               
            }
        }

        private C_PoMaterial InputPacket()
        {
            C_PoMaterial pm = new C_PoMaterial();
            pm.dDate = DateTime.Today;
            pm.Creater = Public.userName;
            pm.cCode = GetNewPacketCode();
            return pm;
        }
        private string GetNewPacketCode()
        {
            string datestr = DateTime.Today.ToString("yyMMdd");

            PoMaterialBLL pmBll = new PoMaterialBLL();
            var rlt = pmBll.GetQuery().Where(p => p.cCode.Substring(0, 6) == datestr).Select(p => new { p.cCode }).ToList();
            if (rlt.Count == 0)
                return string.Format("{0}{1:000}", datestr, 1);
            else
            {
                int seq= int.Parse(rlt.Max(p => p.cCode).Substring(6, 3)) + 1;
                return string.Format("{0}{1:000}", datestr, seq);
            }
        }
        private List<C_PoMaterialList> InputPacketList(DataTable dt, out string msg,out string OutArrMsg)
        {
            List<C_PoMaterialList> lstPm = new List<C_PoMaterialList>();
            Dictionary<string, bool> dicExistInv = new Dictionary<string, bool>();
            Dictionary<string, List<OmsModel>> dicOms = new Dictionary<string, List<OmsModel>>();
            int idx = 1;
            OutArrMsg = "";
            string monthstr = Common.Common.GetShortYearMonthStr(DateTime.Today);
            string prefix = string.Format("M{0}{1:00}", monthstr, DateTime.Today.Day);
            var rlt = new PoMateriallistBLL().Where(p => p.PacketNo.Contains(prefix)).Select(p => new { p.PacketNo }).OrderByDescending(p=>p.PacketNo).ToList();
            int packidx;
            if (rlt.Count>0)
            {
                string max = rlt[0].PacketNo;
                packidx =Common.Common.GetInt(max.Substring(5, 4))+1;
            }
            else
                packidx = 1;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string mocode = dt.Rows[i]["合同号"].ToString().Split('+')[0];
                if (mocode.Trim().Length == 0)
                    continue;
                mocode = mocode.Replace("W0", "WO");
                mocode = mocode.TrimStart().TrimEnd();               
                string abbname= dt.Rows[i]["合同号"].ToString().Split('+')[1];
                string invcode= dt.Rows[i]["存货编码"].ToString();
                string level= dt.Rows[i]["色位"].ToString();
                string seq = dt.Rows[i]["卷号"].ToString();
                int width = Common.Common.GetInt(dt.Rows[i]["幅宽"].ToString().Replace("厘米","").Replace("CM","").Replace("cm",""));
                string invstd = new InventoryBLL().GetQuery().Where(p => p.cInvCode == invcode).Select(p => new { p.cInvStd }).ToList()[0].cInvStd;
                if (GetWidth(invstd) != width)
                {
                    msg = string.Format("第{0}行的存货编码与幅宽不对应，可能编码写错，请检查！", i + 2);
                    return lstPm;
                }
                decimal qty = Common.Common.GetNum(dt.Rows[i]["数量"].ToString());
                string batchno = GeneBatchNo(mocode, abbname, invcode, level.Trim(), seq,out msg);
                if (msg != "")
                {
                    return lstPm;
                }
                var rlt3 = lstPm.Where(p => p.InvCode == invcode && p.BatchNo == batchno).Count();
                if (rlt3 == 0)
                {
                    rlt3 = new ArrivalDetailBLL().Where(p => p.cInvCode == invcode && p.cBatch == batchno).Count();
                    if(rlt3>0)
                    {
                        msg = string.Format("第{0}行的批号已经存在，可能是电子表格中卷号重复，请检查！", i + 2);
                        return lstPm;
                    }
                }
                if (!dicExistInv.ContainsKey(invcode))
                {
                    var invcount = new InventoryBLL().GetQuery().Where(p => p.cInvCode == invcode).Select(p => new { p.cInvCode }).ToList();
                    if (invcount.Count > 0)
                        dicExistInv.Add(invcode,true);
                    else
                    {
                        msg = string.Format("第{0}行存货编码在ERP中不存在，请检查是否录入错误！",i+2);
                        return lstPm;
                    }
                }                

                string packetno = string.Format("{0}{1:0000}", prefix, packidx);
                packidx++;


                C_PoMaterialList pms = new C_PoMaterialList();
                pms.BatchNo = batchno;
                pms.InvCode = invcode;
                pms.Qty = qty;                
                pms.PacketNo = packetno;

                if (!dicOms.ContainsKey(mocode))
                {
                    var rlt2 = new OmDetailBLL().GetQuery().Where(p => p.OM_MOMain.cCode == mocode && p.cInvCode == invcode ).Select(p => new { p.MODetailsID, p.iArrQTY, p.iQuantity }).ToList();
                    if (rlt2.Count == 0)
                    {
                        msg = string.Format("第{0}行存货编码【{1}】对应委外订单【{2}】中不存在，不能入库！", i + 2, invcode, mocode);
                        return lstPm;
                    }
                    List<OmsModel> lstOm = new List<OmsModel>();
                    for (int j = 0; j < rlt2.Count; j++)
                    {
                        OmsModel model = new OmsModel();
                        model.InvCode = invcode;
                        model.OmCode = mocode;
                        model.OmsDid = rlt2[j].MODetailsID;
                        model.AvaArrQty = (decimal)rlt2[j].iQuantity - Common.Common.GetNum(rlt2[j].iArrQTY);
                        lstOm.Add(model);
                    }
                    dicOms.Add(mocode, lstOm);
                }
                List<OmsModel> lstOm1 = dicOms[mocode];
                for (int j = 0; j < lstOm1.Count; j++)
                {
                    if (lstOm1[j].AvaArrQty > 0 || (lstOm1[j].AvaArrQty <=0 && j==lstOm1.Count-1))
                    {
                        pms.PoDid = lstOm1[j].OmsDid;
                        lstOm1[j].AvaArrQty -= (decimal)pms.Qty;
                        break;
                    }
                }
                if (pms.PoDid==null)
                {
                    msg = string.Format("第{0}行存货编码【{1}】对应委外订单【{2}】中到货超出订单数量，不能入库！", i + 2, invcode, mocode);
                    return lstPm;
                }
                lstPm.Add(pms);
            }
            msg = "";
            return lstPm;
        }
        private int GetWidth(string std)
        {
            std = Common.TextUtility.Reversal(std);
            std = std.Substring(0,std.IndexOf('/', 0));
            return Common.Common.GetInt(Common.TextUtility.Reversal(std).Replace("CM", ""));
        }
        /////生成材料暂存表
        /////生成批号
        /////生成入库单
        public string GeneBatchNo(string ContactNo, string CusAbbName,string InvCode, string Level, string seq,out string msg)
        {
            string datestr = DateTime.Today.ToString("yyMMdd");
            var rlt = new OmMainBLL().GetQuery().Where(p => p.cCode == ContactNo).Select(p => new { p.cVenCode }).ToList();
            if (rlt.Count == 0)
            {
                msg = string.Format("委外订单号【{0}】不存在！", ContactNo);
                return "";
            }
            string vencode = rlt[0].cVenCode;
            var rlt1 = new VendorBLL().Where(p => p.cVenCode == vencode).Select(p => new { p.cVenDefine2,p.cVenName }).ToList();
            string abbname1 = rlt1[0].cVenDefine2;
            if (abbname1 == null)
            {
                msg = string.Format("供应商【{0}】未设置拼音简称！",rlt1[0].cVenName);
                return "";
            }
            var rlt2 = new VendorBLL().Where(p => p.cVenDefine3 == CusAbbName).Select(p => new { p.cVenDefine2,p.cVenName }).ToList();
            string abbname2 = "XX";
            if (rlt2.Count > 0)
            {
                abbname2 = rlt2[0].cVenDefine2;
                if (abbname2 == null)
                {
                    msg = string.Format("供应商【{0}】未设置拼音简称！", rlt2[0].cVenName);
                    return "";
                }
            }
            else
            {
                msg = string.Format("供应商【{0}】不存在！", CusAbbName);
                return "";
            }            
            msg = "";
            string batch= string.Format("{0}-{1}-{2}-{3}{4:000}", abbname1, abbname2, datestr, Level == "" ? "X" : Level, Common.Common.GetInt(seq));            
            return batch;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            LoadVouch();
        }

        private void LoadVouch()
        {
            PoMaterialBLL pmBll = new PoMaterialBLL();
            PoMateriallistBLL pdBll = new PoMateriallistBLL();
            var rlt = pdBll.GetQuery().Where(p => p.ISId == null).GroupBy(p => new { p.Id }).Select(p => new { p.Key }).ToList();
            //int count = pmBll.GetQuery().Where(p=>p.C_PoMaterialList.IsId).Select(p => p.Id).Count();
            if (rlt.Count > 0)
            {
                Id = Common.Common.GetInt(rlt[0].Key.Id);
                dgv.Height = this.ClientRectangle.Height - plMain.Height - tspMain.Height;
                dgv.Top = plMain.Bottom;
                ShowPackets(Id);
            }
        }

        private void ShowPackets(int Id)
        {
            string connectionstr = ConfigurationManager.ConnectionStrings["ERPDB"].ToString();
            DbHelperSQL db = new DbHelperSQL(connectionstr);
            PoMaterialBLL pmBll = new PoMaterialBLL();
            C_PoMaterial pm = pmBll.GetEntityByID(Id);
            if (pm == null)
            {
                tbCode.Text = "";
                dtMaker.Value = DateTime.Today;
                tbMaker.Text = Public.userName;
                tbAudit.Text = "";
                this.Id = -1;
                tbArrCode.Text ="";
                dgv.DataSource = null;
                SetTspStatus("保存");
                tsbNewsheet.Enabled = true;
                return;
            }
            tbCode.Text =pm.cCode??"";
            dtMaker.Value=(DateTime)pm.dDate;
            tbMaker.Text =pm.Creater;
            tbAudit.Text =pm.Auditer;
            this.Id = Id;
            tbArrCode.Text = pm.ArriveVouchCode;
            string sql = "select cast(0 as bit) 选择, InvCode as 存货编码,cInvName 存货名称,cInvStd 存货规格,cInvDefine1 颜色,Qty 数量,BatchNo 批号,PacketNo 包号 from EKK..C_PoMaterialList pms left join Inventory inv on pms.InvCode=Inv.cInvCode where pms.ISId is null and pms.Id=" + Id.ToString();
            DataSet ds = db.Query(sql);
            Common.Common.SetDgvData(dgv, ds.Tables[0]);
            dgv.Columns[0].Width = 50;
            dgv.Columns[1].Width = 120;
            dgv.Columns[3].Width = 350;
            dgv.Columns[4].Width = 70;
            dgv.Columns[6].Width = 200;
            if (pm.Auditer != null && pm.Auditer.Trim().Length > 0)
                SetTspStatus("审核");
            else
                SetTspStatus("保存");
        }

        private void tsbSelAll_Click(object sender, EventArgs e)
        {
            dgv.EndEdit();
            for (int i = 0; i < dgv.Rows.Count; i++)
                dgv.Rows[i].Cells[0].Value = true;
            tsbReflash.Enabled = true;
        }

        private void tsbUnSel_Click(object sender, EventArgs e)
        {
            dgv.EndEdit();
            ShowPackets(Id);
        }

        private void tsbPint_Click(object sender, EventArgs e)
        {
            string prnName = Public.GetPrinterName();

            dgv.EndEdit();
            MTab ds = new MTab();
            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                if (!Boolean.Parse(dgv.Rows[i].Cells[0].Value.ToString()))
                    continue;
                DataRow dr = ds.Tables[0].NewRow();
                dr["InvCode"] = dgv.Rows[i].Cells["存货编码"].Value.ToString();
                dr["InvName"] = dgv.Rows[i].Cells["颜色"].Value.ToString()+dgv.Rows[i].Cells["存货名称"].Value.ToString();
                dr["InvStd"] = dgv.Rows[i].Cells["存货规格"].Value.ToString();
                dr["Qty"] = dgv.Rows[i].Cells["数量"].Value.ToString() + "米";
                string batchno = dgv.Rows[i].Cells["批号"].Value.ToString();
                dr["BatchNo"] = batchno;
                string dyeplant = batchno.Split('-')[0];
                string weavplant = batchno.Split('-')[1];
                dr["DyePlant"] = new VendorBLL().Where(p => p.cVenDefine2 == dyeplant).Select(p => new { p.cVenName }).FirstOrDefault().cVenName;
                dr["WeavPlant"] = new VendorBLL().Where(p => p.cVenDefine2 == weavplant).Select(p => new { p.cVenName }).FirstOrDefault().cVenName;
                string packetno =  dgv.Rows[i].Cells["包号"].Value.ToString() ;
                dr["PacketNo"] = packetno;
                EncodingOptions encodeOption = new EncodingOptions();
                encodeOption.Height = 130; // 必须制定高度、宽度
                encodeOption.Width = 300;

                // 2.生成条形码图片并保存
                ZXing.BarcodeWriter wr = new BarcodeWriter();
                wr.Options = encodeOption;
                wr.Format = BarcodeFormat.CODE_128; //  条形码规格：EAN13规格：12（无校验位）或13位数字
                Bitmap img = wr.Write(packetno); // 生成图片
               
                MemoryStream ms = new MemoryStream();
                byte[] imagedata = null;
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                imagedata = ms.GetBuffer();
                dr["BarCode"] = imagedata;                
                ds.Tables[0].Rows.Add(dr);
            }
            //fmReport fmReport = new fmReport();
            crMTab crt = new crMTab();
            crt.SetDataSource(ds);
            crt.PrintOptions.PrinterName = prnName;
            crt.PrintToPrinter(2, true, 1, ds.Tables[0].Rows.Count);
            //fmReport.crystalReportViewer1.ReportSource = crt;
            //fmReport.ShowDialog();
        }

        private void tspMain_Resize(object sender, EventArgs e)
        {
            dgv.Height = this.ClientRectangle.Height - plMain.Height - tspMain.Height;
            dgv.Top = plMain.Bottom;
        }

        private void InitTsp()
        {
            for (int i = 0; i < tspMain.Items.Count; i++)
            {
                tspMain.Items[i].Enabled = false;
            }
        }
        private void SetTspStatus(string status)
        {
            InitTsp();
            switch (status)
            {
                case "新建":
                    tsbNewsheet.Enabled = true;
                    tsbSelAll.Enabled = true;
                    tsbExit.Enabled = true;
                    tsbRetab.Enabled = true;
                    break;
                case "保存":
                    tsbAudit.Enabled = true;
                    tsbSelAll.Enabled = true;
                    tsbExit.Enabled = true;
                    tsbReflash.Enabled = true;
                    tsbRetab.Enabled = true;
                    break;
                case "审核":
                    tsbUnAudit.Enabled = true;
                    tsbSelAll.Enabled = true;
                    tsbPrint.Enabled = true;
                    tsbInStock.Enabled = true;
                    tsbExit.Enabled = true;
                    tsbReflash.Enabled = true;
                    tsbRetab.Enabled = true;
                    break;
            }
        }

        private void tsbAudit_Click(object sender, EventArgs e)
        {
            if (tbAudit.Text.Trim() != "")
                return;
            AuditPM(tbCode.Text.Trim(),true);
            ShowPackets(Id);
            SetTspStatus("审核");
        }

        public bool AuditPM(string code,bool Add)
        {
            string connectionstr = ConfigurationManager.ConnectionStrings["EKKDB"].ToString();
            DbHelperSQL db = new DbHelperSQL(connectionstr);
            string Msg = "";
            int affectrows;
            SqlParameter[] parameters = {
                    new SqlParameter("@PMCode", SqlDbType.NVarChar,20),
                    new SqlParameter("@bAudit", SqlDbType.Bit),
                    new SqlParameter("@Maker", SqlDbType.NVarChar,10),
                    new SqlParameter("@Msg", SqlDbType.NVarChar,200)
                 };
            parameters[0].Value = code;
            parameters[1].Value = Add?1:0;
            parameters[2].Value = Public.userName;
            parameters[3].Direction = ParameterDirection.Output;
            db.RunProcedure("dbo.[CWD_AuditPM]", parameters, out affectrows);
            Msg = parameters[3].Value.ToString();
            if (Msg == "")
                return true;
            else
            {
                MessageBox.Show(Msg, "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
        }
        
        private void tsbInStock_Click(object sender, EventArgs e)
        {
            C_PoMaterial pm = new PoMaterialBLL().GetEntityByID(Id);
            if (pm.Auditer == null || pm.Auditer.Length == 0)
            {
                MessageBox.Show("当前单据未审核，不能入库！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }            
            if (dgv.Rows.Count > 0)
            {
                fmInStock fmIs = new fmInStock();
                fmIs.Id = Id;
                if (fmIs.ShowDialog() == DialogResult.OK)
                    ShowPackets(Id);
            }
        }
       
        private void tsbUnAudit_Click(object sender, EventArgs e)
        {
            if (tbAudit.Text.Trim()=="")
                return;
            AuditPM(tbCode.Text.Trim(),false);
            tbAudit.Text = "";
            tbArrCode.Text = "";         
            ShowPackets(Id);
            SetTspStatus("保存");
        }

        private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int curRow = dgv.CurrentCell.RowIndex;
            dgv.Rows[curRow].Cells[0].Value = !(dgv.Rows[curRow].Cells[0].Value==null?false:Boolean.Parse(dgv.Rows[curRow].Cells[0].Value.ToString()));
            tsbReflash.Enabled = true;
            tsbDelrow.Enabled = true;
        }

        private void tsbExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsbDelrow_Click(object sender, EventArgs e)
        {
            C_PoMaterial pm = new PoMaterialBLL().GetEntityByID(Id);
            if (pm.Auditer != null && pm.Auditer.Length > 0)
            {
                MessageBox.Show("单据已审核，不能删行！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (MessageBox.Show("您确认要删除当前表格选中行吗?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
                return;
            string delpacketno = "";
            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                if (!Boolean.Parse(dgv.Rows[i].Cells[0].Value.ToString()))
                    continue;
                delpacketno += "'"+dgv.Rows[i].Cells["包号"].Value.ToString() + "',";
            }
            delpacketno = delpacketno.TrimEnd(',');
            if (delpacketno == "")
            {
                MessageBox.Show("未删除任何行！", "数据检查", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string connectionstr = ConfigurationManager.ConnectionStrings["ERPDB"].ToString();
            DbHelperSQL db = new DbHelperSQL(connectionstr);           
            string sql = string.Format("delete from ekk..C_PoMaterialList where PacketNo in ({0}) if not exists(select 1 from ekk..C_PoMaterialList where Id = {1}) delete from EKK..C_PoMaterial where ID = {2} ",delpacketno, Id, Id);
            db.ExecuteSql(sql);
            ShowPackets(Id);
            SetTspStatus("保存");
        }

        private void tsbRetab_Click(object sender, EventArgs e)
        {
            fmRetab fmretab = new fmRetab();
            fmretab.ShowDialog();
        }
    }
}
